import random

from deap import base, creator, tools, algorithms

# 创建Fitness和Individual类
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)

# 定义工具箱
N = 100
toolbox = base.Toolbox()
toolbox.register("indices", random.sample, range(N), N)
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)


# 评价函数
def evaluate(individual):
    distance = 0
    for i in range(1, len(individual)):
        distance += distance_matrix[individual[i - 1]][individual[i]]
    distance += distance_matrix[individual[-1]][individual[0]]
    return distance,


toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxOrdered)
toolbox.register("mutate", tools.mutShuffleIndexes, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)

# 遗传算法参数
population = toolbox.population(n=300)
NGEN = 40
CXPB, MUTPB = 0.5, 0.2

# 运行遗传算法
algorithms.eaSimple(population, toolbox, cxpb=CXPB, mutpb=MUTPB, ngen=NGEN,
                    stats=None, halloffame=None, verbose=True)
